package com.agger.harmonyosthemeseditor;

import com.agger.harmonyosthemeseditor.abilities.slices.*;
import com.agger.harmonyosthemeseditor.intelligent.ColorManager;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.FileManager;
import com.agger.harmonyosthemeseditor.intelligent.GeneralUtil;
import com.agger.harmonyosthemeseditor.userinterface.PageSwiper;
import com.agger.harmonyosthemeseditor.userinterface.ResourceTool;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.hms.analytics.HiAnalyticsTools;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.HsvColor;
import ohos.agp.utils.Color;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.configuration.Configuration;
import ohos.global.configuration.DeviceCapability;
import ohos.miscservices.wallpaper.WallpaperController;
import ohos.system.version.SystemVersion;
import ohos.utils.zson.ZSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.security.SecureRandom;

public class ThemesEditorAbility extends Ability
{
    public static boolean isQuitMode = false;
    public static ThemesEditorAbility Instance;
    public static boolean QuitBySelf_Last = false;
    public static boolean isGuideSlice=false,isMainSceneSlice=false;
    public AbilitySlice GuideSlice=null,MainSceneSlice=null;
    //public static HiAnalyticsInstance hiAnalyticsInstance;
    public AGConnectConfig config;
    private int current_Direction;
    public EventRunner eventRunner;
    public static int API_Version_Code = 6;
    public static String ShareFa_Info = "undefined";
    public static boolean LayoutChanged = false;
    public static boolean EnableWallpaperFadeEffect = false;

    public static final int DIMENSION_1X2 = 1;
    public static final int DIMENSION_2X2 = 2;
    public static final int DIMENSION_2X4 = 3;

    private class DirectionChangedEventHandler extends EventHandler
    {
        private DirectionChangedEventHandler(EventRunner runner) {
            super(runner);
        }

        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if(event == null) return;
            if(event.eventId == Configuration.DIRECTION_HORIZONTAL)
            {
                try
                {
                    DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(getContext()).get().getAttributes();
                    if((((float)displayAttributes.width)/((float)displayAttributes.height))>1.48f)
                    getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS|WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION|WindowManager.LayoutConfig.MARK_FULL_SCREEN);
                }
                catch (Exception ex){ex.printStackTrace();}
            }else
            {
                try{getWindow().clearFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS|WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION|WindowManager.LayoutConfig.MARK_FULL_SCREEN);}
                catch (Exception ex){ex.printStackTrace();}
            }
        }
    }

    @Override
    public void onStart(Intent intent)
    {
        Instance = this;
        isQuitMode = false;
        isGuideSlice = false;
        isMainSceneSlice = false;
        LayoutChanged = false;
        GuideSlice = null;
        MainSceneSlice=null;
        //首先需要检测是否为手机或平板环境
        int deviceType = getResourceManager().getDeviceCapability().deviceType;
        if(deviceType == DeviceCapability.DEVICE_TYPE_PHONE || deviceType == DeviceCapability.DEVICE_TYPE_TABLET)
        {
            DatabaseManager.Init(this);
            setColorMode(DatabaseManager.getInt("ColorMode", -1));
            String mDisplayOrientation = DatabaseManager.getString("DisplayOrientation", "UNSPECIFIED");
            if(mDisplayOrientation.equals("PORTRAIT"))
                setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
            else if(mDisplayOrientation.equals("LANDSCAPE"))
                setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE);
            else
                setDisplayOrientation(AbilityInfo.DisplayOrientation.UNSPECIFIED);
            System.gc();
        }
        else DatabaseManager.Init(this);
        super.onStart(intent);
        current_Direction = getResourceManager().getConfiguration().direction;
        eventRunner = EventRunner.current();
        API_Version_Code = SystemVersion.getApiVersion();
        EnableWallpaperFadeEffect = verifySelfPermission("ohos.permission.READ_USER_STORAGE") == IBundleManager.PERMISSION_GRANTED && verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") == IBundleManager.PERMISSION_GRANTED && DatabaseManager.getString("EnableSuperVision", "No").equals("Yes");
        ShareFa_Info = getIntent().getStringParam("sharing_fa_extra_info");
        String GuideFinished = DatabaseManager.getString("GuideFinished","No");
        if(GuideFinished.equals("Yes"))
        {
            // 打开SDK日志开关
            try
            {
                HiAnalyticsTools.enableLog();
                /*应用遵循数据最小化原则，暂不需要采集额外信息
                hiAnalyticsInstance = HiAnalytics.getInstance(Instance);
                hiAnalyticsInstance.setUserProfile("userKey",hiAnalyticsInstance.getAAID());*/
            }catch (Exception ex){ex.printStackTrace();}
            try
            {
                GeneralUtil.writeRawFileToFile(this,"shortcuts_app_manager",getFilesDir()+"/shortcuts_app_manager.png");
                GeneralUtil.writeRawFileToFile(this,"shortcuts_check_update",getFilesDir()+"/shortcuts_check_update.png");
                GeneralUtil.addDynamicShortcuts(GeneralUtil.getAbilityShellActivity(this),new String[]{"AppManager","CheckUpdate"},new String[]{ResourceTool.getString(this,ResourceTable.String_Shortcuts_info,"应用信息"),ResourceTool.getString(this,ResourceTable.String_Shortcuts_update,"检查更新")},new Object[]{GeneralUtil.getBitmapFromFile(getFilesDir()+"/shortcuts_app_manager.png"),GeneralUtil.getBitmapFromFile(getFilesDir()+"/shortcuts_check_update.png")});
            }catch (Exception ex){ex.printStackTrace();}
            if(EnableWallpaperFadeEffect)
            {
                WallpaperController wallpaperController = WallpaperController.getInstance(this);
                boolean result = FileManager.copyFile(wallpaperController.getFile(WallpaperController.WALLPAPER_SYSTEM),getFilesDir()+"/user_wallpaper.jpg");
                if(result)
                    wallpaperController.setWallpaper(GeneralUtil.getColorPixelMap(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_color_bg, Color.getIntColor("#F7EDD8"))),WallpaperController.WALLPAPER_SYSTEM);
            }
            if(ShareFa_Info!=null&&ShareFa_Info.equals("ShareFa_BlindBox"))
            {
                DatabaseManager.setString("LastAbilityName","ThemesBlindBox");
                DatabaseManager.setString("ThemesBlindBox_ModeValue","Unpack");
            }
            boolean QuitBySelf = DatabaseManager.getString("QuitBySelf","No").equals("Yes");
            DatabaseManager.setString("QuitBySelf","No");
            if(QuitBySelf)
            {
                QuitBySelf_Last = true;
                setMainRoute(SplashSceneSlice.class.getName());
            }
            else
            {
                QuitBySelf_Last = false;
                setMainRoute(MainSceneSlice.class.getName());
            }
        }
        else
        {
            QuitBySelf_Last = true;
            setMainRoute(GuideSlice.class.getName());
        }
    }

    public void RebuildWallpaper()
    {
        try
        {
            DatabaseManager.Init(this);
            String GuideFinished = DatabaseManager.getString("GuideFinished","No");
            if(GuideFinished.equals("Yes"))
            {
                WallpaperController wallpaperController = WallpaperController.getInstance(this);
                boolean result = FileManager.copyFile(wallpaperController.getFile(WallpaperController.WALLPAPER_SYSTEM),getFilesDir()+"/user_wallpaper.jpg");
                if(result)
                    wallpaperController.setWallpaper(GeneralUtil.getColorPixelMap(HsvColor.toColor(255,new SecureRandom().nextInt(256),ColorManager.isDarkMode(getContext())?36:12,ColorManager.isDarkMode(getContext())?60:96)),WallpaperController.WALLPAPER_SYSTEM);
            }
        }catch(Exception e){e.printStackTrace();}
    }

    @Override
    public void onForeground(Intent intent)
    {
        if(EnableWallpaperFadeEffect)
        RebuildWallpaper();
        super.onForeground(intent);
    }

    @Override
    public void onBackground()
    {
        if(EnableWallpaperFadeEffect)
        {
            try
            {
                DatabaseManager.Init(this);
                String GuideFinished = DatabaseManager.getString("GuideFinished","No");
                if(GuideFinished.equals("Yes"))
                {
                    WallpaperController wallpaperController = WallpaperController.getInstance(this);
                    if(new File(getFilesDir()+"/user_wallpaper.jpg").exists())
                        wallpaperController.setWallpaper(new FileInputStream(getFilesDir()+"/user_wallpaper.jpg"),WallpaperController.WALLPAPER_SYSTEM);
                }
            }catch(Exception e){e.printStackTrace();}
        }
        super.onBackground();
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent)
    {
        //2.0.0.172新增，设备重启后，可将卡片恢复至上次状态
        if(SystemVersion.getApiVersion()>=5)
        {
            long cardId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY,-1);
            int dimensionId = intent.getIntParam("ohos.extra.param.key.form_dimension",DIMENSION_2X2);
            if(dimensionId==DIMENSION_2X2)
            {
                DatabaseManager.Init(getContext());
                int current = DatabaseManager.getInt("FormBgIndex_"+cardId,0);
                ZSONObject zsonObject = new ZSONObject();
                zsonObject.put("backgroundImage", "/common/background_"+current+".png");
                zsonObject.put("textEntrance", DatabaseManager.getInt("FormTextEntrance_"+cardId,0)==1);
                FormBindingData formBindingData = new FormBindingData(zsonObject);
                try {updateForm(cardId, formBindingData);}catch (Exception e) {}
            }else if(dimensionId==DIMENSION_2X4)
            {
                DatabaseManager.Init(getContext());
                int current = DatabaseManager.getInt("BgMode_"+cardId,0);
                ZSONObject zsonObject = new ZSONObject();
                zsonObject.put("backgroundImage", "/common/background_"+current+".png");
                FormBindingData formBindingData = new FormBindingData(zsonObject);
                try {updateForm(cardId, formBindingData);}catch (Exception e) {}
            }
        }
        return super.onCreateForm(intent);
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message)
    {
        try
        {
            // 解析收到的数据
            ZSONObject messageJSON = ZSONObject.stringToZSON(message);
            if(messageJSON.get("message").equals("updata"))
            {
                ZSONObject zsonObject = new ZSONObject();
                int bound = messageJSON.getIntValue("background_amount");
                //更新卡片json数据
                DatabaseManager.Init(getContext());
                int current = DatabaseManager.getInt("FormBgIndex_"+formId,0);
                int target = new SecureRandom().nextInt(bound);
                if(target==current)
                {
                    target = current+1;
                    target = target>(bound-1)?0:target;
                }
                zsonObject.put("backgroundImage", "/common/background_"+target +".png");
                zsonObject.put("isReady", true);
                FormBindingData formBindingData = new FormBindingData(zsonObject);
                try
                {
                    updateForm(formId, formBindingData);
                    DatabaseManager.setInt("FormBgIndex_"+formId,target);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            super.onTriggerFormEvent(formId, message);
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    @Override
    public boolean supportHighPerformanceUI()
    {
        super.supportHighPerformanceUI();
        return true;
    }

    @Override
    public void onNewIntent(Intent intent)
    {
        ShareFa_Info = intent.getStringParam("sharing_fa_extra_info");
        if(ShareFa_Info!=null&&ShareFa_Info.equals("ShareFa_BlindBox"))
        {
            DatabaseManager.Init(getContext());
            String GuideFinished = DatabaseManager.getString("GuideFinished","No");
            if(GuideFinished.equals("Yes"))
            {
                DatabaseManager.setString("LastAbilityName","ThemesBlindBox");
                DatabaseManager.setString("ThemesBlindBox_ModeValue","Unpack");
                PageSwiper.mainSceneSlice.present(new ThemesBlindBoxSlice(),getIntent());
                ThemesEditorAbility.isMainSceneSlice = false;
            }
        }
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() { }

    @Override
    public void onStop() {super.onStop();}

    @Override
    public void onConfigurationUpdated (Configuration configuration)
    {
        super.onConfigurationUpdated (configuration);
        if(isGuideSlice)
        {
            current_Direction = configuration.direction;
            try
            {
                if(GuideSlice != null)
                    GuideSlice.restart();
            }catch (Exception ex){ex.printStackTrace();}
        }else if(isMainSceneSlice)
        {
            current_Direction = configuration.direction;
            try
            {
                if (MainSceneSlice != null)
                {
                    MainSceneSlice.restart();
                }
            } catch (Exception ex) {ex.printStackTrace();}
        }else
        {
            LayoutChanged = true;
            current_Direction = configuration.direction;
            if(configuration.direction != current_Direction)
            {
                try
                {
                    if(eventRunner != null)
                    {
                        DirectionChangedEventHandler directionChangedEventHandler = new DirectionChangedEventHandler(eventRunner);
                        directionChangedEventHandler.sendEvent(configuration.direction, 0, EventHandler.Priority.IMMEDIATE);
                    }
                }catch (Exception ex){}

            }
            try
            {
                if(SettingsSlice.Instance != null)
                {
                    if (SettingsSlice.Instance.isOnline)
                        SettingsSlice.Instance.ReDialog();
                }
            }catch (Exception ex) {}
            try
            {
                if(AboutSlice.Instance != null)
                {
                    if (AboutSlice.Instance.isOnline)
                        AboutSlice.Instance.ReDialog();
                }
            }catch (Exception ex) {}
        }
    }
}
